﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using Microsoft.Win32;
using LPV_POS.mh_pos;
using LPV_POS;
using System.Data;
using System.Reflection;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Xml;
using System.Xml.Xsl;
using Microsoft.VisualBasic;
using LPV_POS.Module;
using System.Net;
using System.Net.Sockets;
using CrystalDecisions.CrystalReports.Engine;
using DevExpress.XtraGrid.Views.Grid;
//using Microsoft.Office.Interop.Excel;

public class cpublic
{

    #region "   dangnhap"
    public Boolean dangnhap()
    {
        //if(iquyen)
        return true;
    }
    #endregion

    #region "   MaHoa"
    public string MaHoa(string sKhoa, string sMatKhau)
    {
        byte[] utf16 = Encoding.Unicode.GetBytes(sKhoa + "2010" + sMatKhau);
        return Convert.ToBase64String(utf16);
    }
    #endregion

    #region "   GiaiHoa"
    public string GiaiMa(string sKhoa, string sMatKhau)
    {
        if (sKhoa == "")
        {
            byte[] utf = Convert.FromBase64String(sMatKhau);
            return Encoding.Unicode.GetString(utf);
        }
        else
        {
            byte[] utf = Convert.FromBase64String(sMatKhau);
            return Encoding.Unicode.GetString(utf).Replace(sKhoa + "2010", "");
        }

    }
    #endregion

    #region "   ConvertImageToByteArray"
    public byte[] ConvertImageToByteArray(System.Drawing.Imaging.ImageFormat formatOfImage, Image _iHinhAnh)
    {
        byte[] Ret = null;

        try
        {
            if (_iHinhAnh != null)
            {
                Image imageToConvert = _iHinhAnh;
                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    Ret = ms.ToArray();
                }
            }
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }

        return Ret;
    }
    #endregion

    #region "   ConvertByteArrayToImage"
    public Image ConvertByteArrayToImage(Object oHinhAnh)
    {
        try
        {
            if (oHinhAnh + "" != "")
                return this.ConvertByteArrayToImage((byte[])oHinhAnh);
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }

        return null;
    }
    public Image ConvertByteArrayToImage(Byte[] bHinhAnh)
    {
        try
        {
            if (bHinhAnh != null)
            {
                MemoryStream str = new MemoryStream(bHinhAnh);
                return Image.FromStream(str);
            }
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }

        return null;
    }
    #endregion

    #region "   Registry_Set"
    public Boolean Registry_Set(string KeyName, object Value)
    {
        try
        {

            RegistryKey sk1 = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Tcpip\\COMP");//Application.ProductName
            sk1.SetValue(KeyName.ToUpper(), Value);

            return true;
        }
        catch (Exception ex)
        {
            string a = ex.ToString();
            return false;

        }
    }
    #endregion
    //-------06/06/2012-------------------------------
    #region "   Registry_Set1"
    public Boolean Registry_Set1(string KeyName, object Value)
    {
        try
        {

            RegistryKey sk1 = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Tcpip\\COMP1");//Application.ProductName
            sk1.SetValue(KeyName.ToUpper(), Value);

            return true;
        }
        catch (Exception ex)
        {
            string a = ex.ToString();
            return false;

        }
    }
    #endregion
    //-------06/06/2012-------------------------------
    //-------15/08/2012-------------------------------
    #region "   Registry_Set2"
    public Boolean Registry_Set2(string KeyName, object Value)
    {
        try
        {

            RegistryKey sk1 = Registry.CurrentUser.CreateSubKey(@"S-1-5-20\Software\LPV");//Application.ProductName
            sk1.SetValue(KeyName.ToUpper(), Value);

            return true;
        }
        catch (Exception ex)
        {
            string a = ex.ToString();
            return false;

        }
    }
    #endregion
    //-------15/08/2012-------------------------------

    #region "   Registry_Get"
    public string Registry_Get(string KeyName)
    {
        try
        {
            
            RegistryKey sk1 = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Tcpip\COMP");// + Application.ProductName
            

            if (sk1 != null)
            {
                
                return sk1.GetValue(KeyName.ToUpper()) + "";
                
            }
        }
        catch (Exception ex)
        {
            string ss = ex.Message;
            MessageBox.Show(ex.Message);
        }

        return null;
    }
    #endregion

    //-------06/06/2012-------------------------------
    #region "   Registry_Get1"
    public string Registry_Get1(string KeyName)
    {
        try
        {

            RegistryKey sk1 = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Tcpip\\COMP1");// + Application.ProductName


            if (sk1 != null)
            {

                return sk1.GetValue(KeyName.ToUpper()) + "";

            }
        }
        catch (Exception ex)
        {
            string ss = ex.Message;
            MessageBox.Show(ex.Message);
        }

        return null;
    }
    #endregion
    //-------06/06/2012-------------------------------

    //-------06/06/2012-------------------------------
    #region "   Registry_Get2"
    public string Registry_Get2(string KeyName)
    {
        try
        {

            RegistryKey sk1 = Registry.Users.OpenSubKey(@"S-1-5-20\Software\LPV");// + Application.ProductName


            if (sk1 != null)
            {

                return sk1.GetValue(KeyName.ToUpper()) + "";

            }
        }
        catch (Exception ex)
        {
            string ss = ex.Message;
            MessageBox.Show(ex.Message);
        }

        return null;
    }
    #endregion
    //-------06/06/2012-------------------------------

    #region"    IsValidEmailAddress"
    public bool IsValidEmailAddress(string sEmail)
    {
        if (sEmail == null)
        {
            return false;
        }

        int nFirstAT = sEmail.IndexOf('@');
        int nLastAT = sEmail.LastIndexOf('@');

        if ((nFirstAT > 0) && (nLastAT == nFirstAT) &&
        (nFirstAT < (sEmail.Length - 1)))
        {
            // address is ok regarding the single @ sign
            return (System.Text.RegularExpressions.Regex.IsMatch(sEmail, @"(\w+)@(\w+)\.(\w+)"));
        }
        else
        {
            return false;
        }
    }
    #endregion

    #region  goi form chu
    public string loadformchu1(string str_key)
    {
        mh_chu frm_chu = new mh_chu();
        frm_chu.ControlBox = false;
        frm_chu.StartPosition = FormStartPosition.CenterScreen;
        Variable.str_position_frmchu = str_key;
        frm_chu.ShowDialog();
        return Variable.str_chu;
    }

    public string loadformchu_point(int x, int y)
    {
        mh_chu frm_chu = new mh_chu();
        // frm_chu.ControlBox = false;
        Variable.pont_x = x;
        Variable.pont_y = y;
        frm_chu.ShowDialog();
        return Variable.str_chu;
    }
    public string loadformchu_point(string str_key, int x, int y)
    {
        mh_chu frm_chu = new mh_chu();
        // frm_chu.ControlBox = false;
        Variable.pont_x = x;
        Variable.pont_y = y;
        Variable.str_position_frmchu = str_key;
        frm_chu.ShowDialog();
        return Variable.str_chu;
    }


    #endregion

    #region  goi form so
    public string loadformso(string str_key)
    {
        mh_so frm_so = new mh_so();
        // frm_so.ControlBox = false;
        frm_so.StartPosition = FormStartPosition.CenterScreen;
        Variable.str_position_frmso = str_key;
        frm_so.ShowDialog();
        return Variable.str_so;
    }

    public string loadformso_point(int x, int y)
    {
        mh_so frm_so = new mh_so();
        //frm_so.ControlBox = false;
        Variable.pont_x = x;
        Variable.pont_y = y;
        frm_so.ShowDialog();
        return Variable.str_so;
    }

    #endregion


    public bool IsNumeric(string inputString)
    {
        return Microsoft.VisualBasic.Information.IsNumeric(inputString);
        //RETURN TRUE/FALSE

        //return System.Text.RegularExpressions.Regex.IsMatch(inputString, "^[0-9]+$");

    }

    #region "   RemoveSign4VietnameseString"
    /// <summary>
    /// hàm bỏ dấu tiếng việt
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string RemoveSign4VietnameseString(string inputString)
    {
        //string inputString_return = inputString;
        //string[] VietnameseSigns = new string[]{"aAeEoOuUiIdDyY",  "áàạảãâấầậẩẫăắằặẳẵ", "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ", "éèẹẻẽêếềệểễ", "ÉÈẸẺẼÊẾỀỆỂỄ",
        //                                            "óòọỏõôốồộổỗơớờợởỡ", "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ", "úùụủũưứừựửữ", "ÚÙỤỦŨƯỨỪỰỬỮ", "íìịỉĩ",
        //                                            "ÍÌỊỈĨ", "đ", "Đ", "ýỳỵỷỹ", "ÝỲỴỶỸ"
        //                                            };


        //for (int i = 1; i < VietnameseSigns.Length; i++)
        //    for (int j = 0; j < VietnameseSigns[i].Length; j++)
        //    {
        //        inputString_return = inputString_return.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
        //    }
        //return inputString_return;
        return this.utf8_to_ascii(inputString);
    }

    #endregion
    #region "   RemoveSign4VietnameseString"
    // chuoi str la chuoi co dau;
    //ket qua xuat ra chuoi str_ascii la chuoi khong dau;
    // vi du; nhap chuoi "tô hoài chương" ==è "to hoai chuong";

    string utf8_to_ascii(string str)
    {
        string str_ascii = "";
        string chuoi_tk = str;
        string skytu = "";

        char skytuChar = ' ';
        char[] akytuChar = new char[] { '́', '̣', '̀', '̉' };// "̣́̀̉";

        for (int i = 0; i < chuoi_tk.Length; i++)
        {
            int ii = (int)chuoi_tk[i];
            skytu = chuoi_tk[i] + "";
            if (skytu.IndexOf("̃") >= 0)
                continue;
            skytuChar = chuoi_tk[i];
            //
            foreach (char ch in akytuChar)
                if (skytuChar == ch)
                    goto tieptuc;
            //            
            switch (skytu)
            {
                #region "A"
                case "Ấ":
                case "Ầ":
                case "Ẩ":
                case "Ẫ":
                case "Ậ":
                case "Ắ":
                case "Ằ":
                case "Ẳ":
                case "Ẵ":
                case "Ặ":
                case "Á":
                case "À":
                case "Ả":
                case "Ã":
                case "Ạ":
                case "Â":
                case "Ă":
                    str_ascii += "A";
                    break;
                #endregion

                #region "a"
                case "ấ":
                case "ầ":
                case "ẩ":
                case "ẫ":
                case "ậ":
                case "ắ":
                case "ằ":
                case "ẳ":
                case "ẵ":
                case "ặ":
                case "á":
                case "à":
                case "ả":
                case "ã":
                case "ạ":
                case "â":
                case "ă":
                    str_ascii += "a";
                    break;
                #endregion

                #region "E"
                case "Ế":
                case "Ề":
                case "Ể":
                case "Ễ":
                case "Ệ":
                case "É":
                case "È":
                case "Ẻ":
                case "Ẽ":
                case "Ẹ":
                case "Ê":
                    str_ascii += "E";
                    break;
                #endregion

                #region "e"
                case "ế":
                case "ề":
                case "ể":
                case "ễ":
                case "ệ":
                case "é":
                case "è":
                case "ẻ":
                case "ẽ":
                case "ẹ":
                case "ê":
                    str_ascii += "e";
                    break;
                #endregion

                #region "   I"
                case "Í":
                case "Ì":
                case "Ỉ":
                case "Ĩ":
                case "Ị":
                    str_ascii += "I";
                    break;
                #endregion

                #region "   i"
                case "í":
                case "ì":
                case "ỉ":
                case "ĩ":
                case "ị":
                    str_ascii += "i";
                    break;
                #endregion

                #region "   O"
                case "Ố":
                case "Ồ":
                case "Ổ":
                case "Ô":
                case "Ộ":
                case "Ớ":
                case "Ờ":
                case "Ở":
                case "Ỡ":
                case "Ợ":
                case "Ó":
                case "Ò":
                case "Ỏ":
                case "Õ":
                case "Ọ":
                case "Ơ":
                    str_ascii += "O";
                    break;
                #endregion

                #region "   o"
                case "ố":
                case "ồ":
                case "ổ":
                case "ỗ":
                case "ộ":
                case "ớ":
                case "ờ":
                case "ở":
                case "ỡ":
                case "ợ":
                case "ó":
                case "ò":
                case "ỏ":
                case "õ":
                case "ọ":
                case "ô":
                case "ơ":
                    str_ascii += "o";
                    break;
                #endregion

                #region "   U"
                case "Ứ":
                case "Ừ":
                case "Ử":
                case "Ữ":
                case "Ự":
                case "Ú":
                case "Ù":
                case "Ủ":
                case "Ũ":
                case "Ụ":
                case "Ư":
                    str_ascii += "U";
                    break;
                #endregion

                #region "   u"
                case "ứ":
                case "ừ":
                case "ử":
                case "ữ":
                case "ự":
                case "ú":
                case "ù":
                case "ủ":
                case "ũ":
                case "ụ":
                case "ư":
                    str_ascii += "u";
                    break;
                #endregion

                #region "   y d "
                case "ý":
                case "ỳ":
                case "ỷ":
                case "ỹ":
                case "ỵ":
                    str_ascii += "y";
                    break;
                case "Ý":
                case "Ỳ":
                case "Ỷ":
                case "Ỹ":
                case "Ỵ":
                    str_ascii += "Y";
                    break;
                case "đ":
                    str_ascii += "d";
                    break;
                case "Đ":
                    str_ascii += "D";
                    break;
                case "%20":
                    str_ascii += "_";
                    break;
                #endregion
                default:
                    str_ascii += chuoi_tk[i];
                    break;
            }
        tieptuc:
            skytu = skytu + "";
        }
        return str_ascii;
    }
    #endregion
    public string Spacestring(int i)
    {
        string chuoi = "";
        if (i >= 0)
            //{
            //    for (int index = 1; index <= i; index++)
            //    {
            //        chuoi += " ";
            //    }
            //}
            chuoi = new String(' ', i);
        return chuoi;
    }

    #region "   splitString"
    public string[] splitString(string sNoiDung, int iChieuDai)
    {//chia chuoi thanh 2 dong, neu qua dai.
        string sNoiDung1 = "";
        string sNoiDung2 = "";
        if (sNoiDung.Length >= iChieuDai)
        {
            int iSpace = 0;
            int icount = 0;
            while (icount < iChieuDai)
            {
                if (sNoiDung.IndexOf(' ', icount) == icount)
                    iSpace = icount;
                icount++;
            }

            sNoiDung1 = sNoiDung.Substring(0, iSpace).Trim();
            sNoiDung2 = sNoiDung.Substring(iSpace).Trim();
        }
        if (sNoiDung2.Trim() != "")
            return new string[] { sNoiDung1, sNoiDung2 };
        else if (sNoiDung1.Trim() != "")
            return new string[] { sNoiDung1 };
        else
            return new string[] { sNoiDung };
    }
    #endregion

    #region "   Clone Object"
    //private System.Windows.Forms.Control CloneObject(System.Windows.Forms.Control o)
    //{
    //    Type t = o.GetType();
    //    PropertyInfo[] properties = t.GetProperties();

    //    System.Windows.Forms.Control p = (System.Windows.Forms.Control)t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);

    //    foreach (PropertyInfo pi in properties)
    //    {
    //        if (pi.CanWrite)
    //        {
    //            pi.SetValue(p, pi.GetValue(o, null), null);
    //        }
    //    }
    //    p.Name = o.Name + "1";
    //    return p;
    //}

    #endregion

    #region "   ngay lam viec"
    public void get_ngay_lam_viec()
    {
        DataTable tbTMP = new thuvien().SP_SelectDataTable("sp_BH_CAU_HINH",
                                                    new string[] { "@flag" },
                                                    new object[] { 4 });

        if (tbTMP.Rows[0]["NGAY_LAM_VIEC"] + "" != "" && (Boolean)tbTMP.Rows[0]["NGAY_LAM_VIEC_LA_NGAY_HE_THONG"] == false)
        {
            Variable.ngay_lamviec = (DateTime)tbTMP.Rows[0]["NGAY_LAM_VIEC"];
        }
        else
        {
            tbTMP = new thuvien().SP_SelectDataTable("SP_EXECUTESQL",
                                                                new string[] { "@sSQL" },
                                                                new object[] { "SELECT GETDATE()" });
            if (tbTMP.Select().Length > 0)
                Variable.ngay_lamviec = (DateTime)tbTMP.Rows[0][0];
        }
    }
    #endregion

    #region "    BoGoc_Control"

    #region "   BoGoc_Control"
    public void BoGoc_Control(System.Windows.Forms.Control _Control, Color BackColor, Color ForeColor, Color BorderColor, System.Drawing.Font TextFont, bool ApplyBorder)
    {
        if (_Control.ToString().ToLower().IndexOf("label") >= 0)
        {
            ((Label)_Control).Image = null;
            ((Label)_Control).BorderStyle = BorderStyle.None;
        }

        Bitmap ihinh = this.GetRoundedRectangle(BackColor, ForeColor, BorderColor, TextFont, ApplyBorder, _Control.Text, _Control.Width, _Control.Height);
        this.SetImageText(ihinh, _Control.Text, ForeColor, TextFont, _Control.Width, _Control.Height);
        _Control.BackgroundImage = ihinh;
        _Control.Tag = _Control.Text;
        _Control.Text = "";
        _Control.BackColor = System.Drawing.Color.Transparent;

    }
    #endregion

    #region "   Get Rounded Rectangle"
    //Bitmap GetRoundedRectangle(System.Windows.Forms.Control _Control, Color BackColor, Color ForeColor, Color BorderColor, System.Drawing.Font TextFont, bool ApplyBorder, string text, int width, int height)
    Bitmap GetRoundedRectangle(Color BackColor, Color ForeColor, Color BorderColor, Font TextFont, bool ApplyBorder, string text, int width, int height)
    {
        int iCornerSize = 10;//_Control
        Size CornerSize = new Size(iCornerSize, iCornerSize);
        int x = 0;
        int y = 0;

        int w = width;
        int h = height;
        int xr = Convert.ToInt32(w - (x + CornerSize.Width)) - 3;
        int yr = Convert.ToInt32(h - (y + CornerSize.Height)) - 3;
        int iw = Convert.ToInt32(w - xr);
        int ih = Convert.ToInt32(h - yr);

        float sweepAngle = 90.0f;
        Bitmap bm = null;
        SolidBrush fillBrush;
        Color FillColor;

        try
        {
            bm = new Bitmap(w, h, PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(bm);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle bgImg = new Rectangle(0, 0, w, h);

            Rectangle tl = new Rectangle(x, y, CornerSize.Width, CornerSize.Height);
            Rectangle tr = new Rectangle(xr, y, CornerSize.Width, CornerSize.Height);
            Rectangle bl = new Rectangle(x, yr, CornerSize.Width, CornerSize.Height);
            Rectangle br = new Rectangle(xr, yr, CornerSize.Width, CornerSize.Height);

            Rectangle innerRect = new Rectangle(x, iCornerSize / 2, w - 3, h - iCornerSize - 3);

            GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();

            //path.AddArc(tl, 180, sweepAngle);
            //path.AddArc(tr, 270, sweepAngle);
            //path.AddRectangle(innerRect);
            //path.AddArc(bl, 90, sweepAngle);
            //path.AddArc(br, 360, sweepAngle);

            path.AddArc(tl, 180, sweepAngle);
            path.AddArc(tr, 270, sweepAngle);
            path.AddRectangle(innerRect);
            path.AddArc(bl, 90, sweepAngle);
            path.AddArc(br, 360, sweepAngle);

            FillColor = BackColor;
            fillBrush = new SolidBrush(FillColor);
            path.CloseAllFigures();
            g.FillPath(fillBrush, path);
            fillBrush.Dispose();

            #region "   Border"
            if (ApplyBorder)
            {
                Pen borderPen = new Pen(BorderColor, 1);
                Pen fillPen = new Pen(FillColor, 1);

                g.DrawPath(borderPen, path);

                g.DrawLine(fillPen, innerRect.Left + 1, innerRect.Top, innerRect.Width + (x - 1), innerRect.Top);
                g.DrawLine(fillPen, innerRect.Left + 1, innerRect.Bottom, innerRect.Width + (x - 1), innerRect.Bottom);

                fillPen.Dispose();
                borderPen.Dispose();
            }
            #endregion
            g.Dispose();
        }
        catch (Exception e)
        {
            throw e;
        }
        return bm;
    }
    public Bitmap SetImageText(System.Windows.Forms.Control _Control)
    {
        return this.SetImageText((Bitmap)_Control.BackgroundImage, _Control.Text, _Control.ForeColor, _Control.Font, _Control.Width, _Control.Height);
    }
    public Bitmap SetImageText(Bitmap _image, string text, Color ForeColor, Font TextFont, int width, int height)
    {
        int iCornerSize = 10;//_Control
        int x = 0;
        int w = width;
        int h = height;

        #region "   Text"
        Graphics g = Graphics.FromImage(_image);
        if (text.Length > 0)
        {
            SolidBrush TextBrush = new SolidBrush(ForeColor);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.Trimming = StringTrimming.EllipsisCharacter;
            sf.LineAlignment = StringAlignment.Center;
            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

            Rectangle innerRect = new Rectangle(x, iCornerSize / 2, w - 3, h - iCornerSize - 3);
            g.DrawString(text, TextFont, TextBrush, innerRect, sf);

            TextBrush.Dispose();
            sf.Dispose();
        }
        g.Dispose();
        #endregion

        return _image;
    }
    #endregion

    #region "   BoGoc_Control_KhongText"
    public Bitmap BoGoc_Control_KhongText(System.Windows.Forms.Control _Control, Color BackColor, Color ForeColor, Color BorderColor, System.Drawing.Font TextFont, bool ApplyBorder)
    {
        if (_Control.ToString().ToLower().IndexOf("label") >= 0)
        {
            ((Label)_Control).Image = null;
            ((Label)_Control).BorderStyle = BorderStyle.None;
        }
        if (_Control.BackgroundImage == null)
        {
            _Control.BackgroundImage = this.GetRoundedRectangle(BackColor, ForeColor, BorderColor, TextFont, ApplyBorder, _Control.Text, _Control.Width, _Control.Height);
        }
        _Control.BackColor = System.Drawing.Color.Transparent;

        return (Bitmap)_Control.BackgroundImage;
    }
    #endregion


    #endregion

    #region "   luuControl"
    #region "   luuControl_Format"
    public void luuControl_Format(string Tu_Khoa, System.Windows.Forms.Control ctrl)
    {
        if (Tu_Khoa.Trim() == "")
        {
            new mh_thongbao("Lưu Control \n Nhập từ khóa", 2).ShowDialog();
            return;
        }


        string str = "";
        str += ctrl.BackColor.Name + "#";//0
        str += ctrl.Location.X + "#";//1
        str += ctrl.Location.Y + "#";//2
        str += ctrl.Size.Width + "#";//3
        str += ctrl.Size.Height + "#";//4
        str += ctrl.Font.Name + "#";//5            
        str += ctrl.Font.Size + "#";//6
        str += ctrl.Font.Style + "#";//7
        str += ctrl.ForeColor.R + "#";//8
        str += ctrl.ForeColor.G + "#";//9
        str += ctrl.ForeColor.B + "#";//10

        str += ctrl.BackColor.R + "#";//11.R
        str += ctrl.BackColor.G + "#";//12.G
        str += ctrl.BackColor.B + "#";//13.B
        str += ctrl.Region + "#";//14.Region

        this.Registry_Set(Tu_Khoa + "Format", str);
    }
    #endregion

    #region "   loadControl"
    public void loadControl_Format(string Tu_Khoa, System.Windows.Forms.Control ctrl)
    {
        //
        try
        {
            string s = ctrl.Text;
            if (s == "VIP A8")
                s = s + "";
            Color oColor = (Color)(new ColorConverter().ConvertFromString("Yellow"));

            //cpublic ocpublic = new cpublic();
            string xyA1 = this.Registry_Get(Tu_Khoa + "Format");
            if (xyA1 != null)
                if (xyA1 != "" && xyA1.IndexOf("#") > 0)
                {
                    //0.BackColor-FromName
                    string sMauNen = xyA1.Split('#')[0] + "";
                    Color cMauNen = Color.FromName(sMauNen);
                    ctrl.BackColor = cMauNen;

                    //1.2.Location
                    int Lx = int.Parse("0" + xyA1.Split('#')[1]);// Location X
                    int Ly = int.Parse("0" + xyA1.Split('#')[2]);//Location Y
                    ctrl.Location = new Point(Lx, Ly);

                    //3.4.Size
                    int Sx = int.Parse("0" + xyA1.Split('#')[3]);//Size X//
                    int Sy = int.Parse("0" + xyA1.Split('#')[4]);//Size Y
                    ctrl.Size = new Size(Sx, Sy);

                    //5.Font.Name //6.Font.Size //7.Font.Style
                    string sFonrName = xyA1.Split('#')[5] + "";
                    float sFontSize = float.Parse("0" + xyA1.Split('#')[6]);
                    string sFontStyle = xyA1.Split('#')[7] + "";
                    ctrl.Font = new Font(sFonrName, sFontSize, this.getFontStyle(sFontStyle), GraphicsUnit.Point, ((byte)(0)));

                    //8.ForeColor-FromArgb
                    int iMauChuR = int.Parse("0" + xyA1.Split('#')[8]);
                    int iMauChuG = int.Parse("0" + xyA1.Split('#')[9]);
                    int iMauChuB = int.Parse("0" + xyA1.Split('#')[10]);
                    ctrl.ForeColor = Color.FromArgb(iMauChuR, iMauChuG, iMauChuB);

                    //11.BackColor-FromArgb //10. //11.
                    int iMauNenR = int.Parse("0" + xyA1.Split('#')[11]);
                    int iMauNenG = int.Parse("0" + xyA1.Split('#')[12]);
                    int iMauNenB = int.Parse("0" + xyA1.Split('#')[13]);
                    cMauNen = Color.FromArgb(iMauNenR, iMauNenG, iMauNenB);
                    ctrl.BackColor = cMauNen;

                    //14.Region
                    object sRegion = xyA1.Split('#')[14];
                    if (sRegion + "" != "")
                        this.convert2LabelHinhTron(ctrl);


                    this.Refresh(ctrl);
                }
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }
    }
    #region "   convert2LabelHinhTron"
    void convert2LabelHinhTron(System.Windows.Forms.Control ctrl)
    {
        GraphicsPath Gp = new GraphicsPath();
        Gp.AddEllipse(0, 0, ctrl.Size.Width - 1, ctrl.Size.Height - 1);
        ctrl.Region = new Region(Gp);
        Gp.Dispose();
    }
    #endregion

    #region "   Refresh"
    void Refresh(System.Windows.Forms.Control ctrl)
    {
        if (ctrl.ToString().IndexOf("Label") >= 0)
        {
            if (ctrl.Parent.Region != null)
                this.convert2LabelHinhTron(ctrl.Parent);
        }
        else if (ctrl.Region != null)
            this.convert2LabelHinhTron(ctrl);
    }
    #endregion

    #region "   getFontStyle"
    private FontStyle getFontStyle(string FontStyleName)
    {
        if (FontStyleName.IndexOf("Bold") >= 0 && FontStyleName.IndexOf("Italic") >= 0)
            return (FontStyle)((FontStyle.Bold | FontStyle.Italic));
        else if (FontStyleName.IndexOf("Bold") >= 0)
            return FontStyle.Bold;
        else if (FontStyleName.IndexOf("Italic") >= 0)
            return FontStyle.Italic;
        else
            return FontStyle.Regular;
    }
    #endregion
    #endregion

    #region "   luuControl_FontColor"
    public void luuControl_FontColor(string Tu_Khoa, System.Windows.Forms.Control ctrl)
    {
        if (Tu_Khoa.Trim() == "")
        {
            new mh_thongbao("Lưu Control \n Nhập từ khóa", 2).ShowDialog();
            return;
        }
        string str = "";
        str += ctrl.Font.Name + "#";//0
        str += ctrl.Font.Size + "#";//1
        str += ctrl.Font.Style + "#";//2

        str += ctrl.ForeColor.R + "#";//3
        str += ctrl.ForeColor.G + "#";//4
        str += ctrl.ForeColor.B + "#";//5

        str += ctrl.BackColor.R + "#";//6.R
        str += ctrl.BackColor.G + "#";//7.G
        str += ctrl.BackColor.B + "#";//8.B

        this.Registry_Set(Tu_Khoa + "FontColor", str);
    }
    #endregion

    #region "   loadControl_FontColor"
    public void loadControl_FontColor(string Tu_Khoa, System.Windows.Forms.Control ctrl)
    {
        if (Tu_Khoa.Trim() == "")
        {
            new mh_thongbao("Lưu Control \n Nhập từ khóa", 2).ShowDialog();
            return;
        }
        try
        {
            string xyA1 = this.Registry_Get(Tu_Khoa + "FontColor");
            if (xyA1 != null)
                if (xyA1 != "" && xyA1.IndexOf("#") > 0)
                {
                    //0.Font.Name //1.Font.Size //2.Font.Style
                    string sFonrName = xyA1.Split('#')[0] + "";
                    float sFontSize = float.Parse("0" + xyA1.Split('#')[1]);
                    string sFontStyle = xyA1.Split('#')[2] + "";
                    ctrl.Font = new Font(sFonrName, sFontSize, this.getFontStyle(sFontStyle), GraphicsUnit.Point, ((byte)(0)));

                    //3.ForeColor-FromArgb
                    int iMauChuR = int.Parse("0" + xyA1.Split('#')[3]);
                    int iMauChuG = int.Parse("0" + xyA1.Split('#')[4]);
                    int iMauChuB = int.Parse("0" + xyA1.Split('#')[5]);
                    ctrl.ForeColor = Color.FromArgb(iMauChuR, iMauChuG, iMauChuB);

                    //6.BackColor-FromArgb //10. //11.
                    int iMauNenR = int.Parse("0" + xyA1.Split('#')[6]);
                    int iMauNenG = int.Parse("0" + xyA1.Split('#')[7]);
                    int iMauNenB = int.Parse("0" + xyA1.Split('#')[8]);
                    ctrl.BackColor = Color.FromArgb(iMauNenR, iMauNenG, iMauNenB);
                }
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }
    }
    #endregion
    #endregion

    #region "   Load_tbBH_CAU_HINH"
    public void Load_tbBH_CAU_HINH()
    {
        thuvien othuvien = new thuvien();
        string sSQL = "SELECT * FROM BH_CAU_HINH";
        Variable.tbBH_CAU_HINH = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
        //
        sSQL = "SELECT * FROM DM_LOAIDICHVU";
        Variable.tbDM_LOAIDICHVU = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
            //
        string objNAME_KHO = this.Registry_Get("frmBH_CAU_HINH" + "cboKHO_MACDINH");

        Variable.ma_khohang = objNAME_KHO;
        if (objNAME_KHO + "" == "")
            MessageBox_LPV.Show("Chưa chọn cấu hình KHO MẶC ĐỊNH bán hàng");
    }
    #endregion

    #region "   Load_tbMENU_QUYEN"
    //public 
    DataTable Load_tbMENU_QUYEN()
    {
        Int64 iquyen = Variable.iquyen;

        string sSQL = "SELECT CHON = CAST(0 AS BIT), menu_ma, ten_form, ten_control, tag_control, menu_tieude FROM MENU ORDER BY menu_ma";
        DataTable _tbMENU_QUYEN = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });

        int imaxMenu_id = 0;
        int.TryParse(_tbMENU_QUYEN.Rows[_tbMENU_QUYEN.Rows.Count - 1]["menu_ma"] + "", out imaxMenu_id);
        for (imaxMenu_id = imaxMenu_id + 0; imaxMenu_id >= 0; imaxMenu_id--)
        {
            double itest = Math.Pow(2, imaxMenu_id);
            if (Math.Pow(2, imaxMenu_id) <= iquyen && Math.Pow(2, imaxMenu_id) > iquyen / 2)
            {
                if (_tbMENU_QUYEN.Select("menu_ma=" + imaxMenu_id).Length == 1)
                    _tbMENU_QUYEN.Select("menu_ma=" + imaxMenu_id)[0]["CHON"] = true;
                iquyen = iquyen - (Int64)Math.Pow(2, imaxMenu_id);
            }
        }

        return _tbMENU_QUYEN;
    }
    #endregion

    public Boolean KiemTra_CoQuyen(string _TenForms, string _TenControl_TagControl, int _i1TenControl_2TagControl)
    {
        DataTable tb = Load_tbMENU_QUYEN();
        if (_i1TenControl_2TagControl == 1)
            return tb.Select("ten_form LIKE '" + _TenForms + "' AND ten_control LIKE '" + _TenControl_TagControl + "' AND CHON = TRUE").Length > 0;
        else if (_i1TenControl_2TagControl == 2)
            return tb.Select("ten_form LIKE '" + _TenForms + "' AND tag_control LIKE '" + _TenControl_TagControl + "' AND CHON = TRUE").Length > 0;
        return false;
    }

    #region "   ExportExcel"
    public void ExportExcel(DataSet ds, String _FileFullName)
    {
        Microsoft.Office.Interop.Excel.Application oApplication;
        Microsoft.Office.Interop.Excel.Workbook oWorkbook;
        Microsoft.Office.Interop.Excel.Worksheet oWorksheet;
        Microsoft.Office.Interop.Excel.Range oRange;
        try
        {


            // Start Excel and get Application object.
            oApplication = new Microsoft.Office.Interop.Excel.Application();

            // Set some properties
            oApplication.Visible = true;
            oApplication.DisplayAlerts = false;

            // Get a new workbook.
            oWorkbook = oApplication.Workbooks.Add(Missing.Value);

            // Get the active sheet
            oWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)oWorkbook.ActiveSheet;
            oWorksheet.Name = ds.Tables[0].TableName;

            // Process the DataTable
            // BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE


            int rowCount = 1;
            int irow = 0;
            foreach (DataTable dt in ds.Tables)
            {
                irow = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    rowCount += 1;
                    for (int i = 1; i < dt.Columns.Count + 1; i++)
                    {
                        try
                        {
                            // Add the header the first time through
                            if (irow == 1)
                            {
                                oWorksheet.Cells[rowCount - 1, i] = dt.Columns[i - 1].ColumnName;
                            }
                            oWorksheet.Cells[rowCount, i] = dr[i - 1].ToString();
                        }
                        catch
                        {
                        }
                    }
                    irow++;
                }
                if (dt.Columns.Count > 0)
                    rowCount += 2;
                // Resize the columns
                oRange = oWorksheet.get_Range(oWorksheet.Cells[1, 1], oWorksheet.Cells[rowCount, dt.Columns.Count]);
                oRange.EntireColumn.AutoFit();
            }
            // Save the sheet and close
            oWorksheet = null;
            oRange = null;
            oWorkbook.SaveAs(_FileFullName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            oWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
            oWorkbook = null;
            oApplication.Quit();
            if (File.Exists(_FileFullName))
            {
                System.Diagnostics.Process.Start(_FileFullName);//mo file vừa SAVE = DOUBLE_LICK
            }
            // Clean up
            // NOTE: When in release mode, this does the trick

        }
        catch (Exception ex)
        {

        }
        finally
        {
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
    }
    #endregion

    #region "chuyen chuoi thành số có dấu phân cach"
    private string f_convert_string_into_money_1(string p_str)  // 123456 ---> 123,456
    {

        #region "cach 1"
        //string _ketqua = "";
        //string _temp = "";
        //decimal _number_temp;
        //int vitri = 1;
        //p_str = p_str.Replace(",", "");
        //p_str = p_str.Replace(".", "");
        //if (decimal.TryParse(p_str, out _number_temp))
        //{
        //    for (int i = p_str.Length - 1; i >= 0; i--)
        //    {
        //        _temp += p_str[i];
        //        if (vitri % 3 == 0)
        //            _temp += ",";
        //        vitri++;
        //    }
        //    for (int i = _temp.Length - 1; i >= 0; i--)
        //        _ketqua += _temp[i];
        //    if (_ketqua[0] == ',')
        //        _ketqua = _ketqua.Substring(1, _ketqua.Length - 1);
        //}
        //else
        //    _ketqua = "";
        //return _ketqua;
        #endregion

        #region "Cách 2"
        string _ketqua = "";
        decimal _number_temp;
        p_str = p_str.Replace(",", "");
        p_str = p_str.Replace(".", "");
        if (decimal.TryParse(p_str, out _number_temp))
            _ketqua = _number_temp.ToString("N0");
        else
            _ketqua = "";
        return _ketqua;
        #endregion


    }

    //--------------------------------------------------------------
    //     Chức năng: chuyển chuỗi số 1234567 thành 1,234,567 hoặc 1234567.123 thành 1,234,567.123
    //      return chuỗi rỗng nếu không phải là chuỗi số, nguoc lai tra về chuỗi đã chuyển.
    //--------------------------------------------------------------
    public string f_convert_string_into_number(string p_str)
    {
        string _ketqua = "";
        if (p_str.Split('.').Length == 2)
        {
            _ketqua = f_convert_string_into_money_1(p_str.Split('.')[0]);
            if (_ketqua == "")
                return _ketqua;
            else
                _ketqua = _ketqua + "." + p_str.Split('.')[1];
        }
        else if (p_str.Split('.').Length == 1)
        {
            _ketqua = f_convert_string_into_money_1(p_str);
        }
        return _ketqua;

    }

    #endregion

    #region "chuyen so thanh chu"
    public string ChuyenSo_ThanhChu(string pstrNum)
    {
        string tempgfReadNumVie = null;
        int bytX = 0;
        int bytsolan = 0;
        int intcount = 0;

        string strcum = null;
        string[] ArrStrdolon = { "", "", " ngàn", " triệu", " tỷ", " ngàn", " triệu", " tỷ tỷ", " ngàn", " triệu", " tỷ tỷ tỷ" };

        bool blntri = false;
        bool blndoclai = false;

        tempgfReadNumVie = "";

        try
        {
            pstrNum = System.Convert.ToInt64(pstrNum).ToString("####").Trim(' ');
            bytX = pstrNum.Length % 3;
            pstrNum = ((bytX > 0) ? new String(' ', 3 - bytX) : "") + pstrNum;
            bytsolan = pstrNum.Length / 3;

            if (bytsolan > 10)
            {
                return tempgfReadNumVie;
            }

            for (intcount = 1; intcount <= pstrNum.Length - 2; intcount += 3)
            {
                strcum = pstrNum.Substring(intcount - 1, 3);
                if (Convert.ToInt32(strcum) > 0)
                {
                    tempgfReadNumVie = tempgfReadNumVie + fDoc3so(strcum, blntri) + ArrStrdolon[bytsolan];
                    blntri = true;
                }
                else
                {
                    if ((bytsolan - 1) % 3 == 0)
                    {
                        //INSTANT C# NOTE: The following VB 'Select Case' included range-type or non-constant 'Case' expressions and was converted to C# 'if-else' logic:
                        //                      Select Case intcount
                        //ORIGINAL LINE: Case Is > 9
                        if (intcount > 9)
                        {
                            blndoclai = Convert.ToInt32(pstrNum.Substring(intcount - 6 - 1, 9)) > 0;
                        }
                        //ORIGINAL LINE: Case Else
                        else
                        {
                            blndoclai = Convert.ToInt32(pstrNum.Substring(0, intcount + 2)) > 0;
                        }
                        if (blndoclai)
                        {
                            tempgfReadNumVie = tempgfReadNumVie + ArrStrdolon[bytsolan];
                        }
                    }
                }
                bytsolan = bytsolan - 1;
            }

            tempgfReadNumVie = tempgfReadNumVie.TrimStart(' ');
            tempgfReadNumVie = tempgfReadNumVie.Substring(0, 1).ToUpper() + tempgfReadNumVie.Substring(1);
        }
        catch (Exception ex)
        {
            //MessageBox.Show(mArrStrFrmMess(2) + System.Environment.NewLine + " mdlReport - gfReadNumVie " + System.Environment.NewLine + ex.Message, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {

        }
        return tempgfReadNumVie;
    }

    private string fDoc3so(string pstrNum, bool pblnle)
    {
        string tempfDoc3so = null;
        byte bytNum1 = 0;
        byte bytNum2 = 0;
        byte bytNum3 = 0;
        string[] ArrStrchu = { "", " một", " hai", " ba", " bốn", " năm", " sáu", " bảy", " tám", " chín" };

        tempfDoc3so = "";

        try
        {
            pstrNum = System.Convert.ToInt64(pstrNum).ToString("000");
            bytNum1 = Convert.ToByte(pstrNum.Substring(0, 1));
            bytNum2 = Convert.ToByte(pstrNum.Substring(1, 1));
            bytNum3 = Convert.ToByte(pstrNum.Substring(pstrNum.Length - 1));
            tempfDoc3so = ((bytNum1 > 0) ? ArrStrchu[bytNum1] + " trăm" : (pblnle ? " không trăm" : ""));
            pblnle = ((bytNum2 > 0) ? false : ((bytNum3 > 0) ? (bytNum1 > 0) | (bytNum1 == 0 && pblnle) : false));
            tempfDoc3so = tempfDoc3so + ((bytNum2 > 1) ? ArrStrchu[bytNum2] + " mươi" : ((bytNum2 == 1) ? " mười" : (pblnle ? " lẻ" : "")));
            tempfDoc3so = tempfDoc3so + ((bytNum2 > 1 && bytNum3 == 1) ? " mốt" : ((bytNum2 > 0 && bytNum3 == 5) ? " lăm" : ArrStrchu[bytNum3]));
        }
        catch (Exception ex)
        {

        }
        finally
        {
        }
        return tempfDoc3so;
    }



    #endregion

    #region "   Send_DuLieu_Den_MayInCOM"
    // send du lieu den 1 may tinh co gan may in COM
    /// <summary>
    /// 
    /// </summary>
    /// <param name="loai_in">bep; hoadon; thanhtoan</param>
    /// <param name="sDM_MAYIN_MA">Chi co in bep moi nhap thông số này</param>
    /// <param name="_data"></param>
    /// <param name="IPMay_Nhan_DuLieu"></param>
    /// <param name="sPort_May_Nhan_DuLieu"></param>
    public void Send_DuLieu_Den_MayInCOM(string loai_in, string sDM_MAYIN_MA, string _data, string IPMay_Nhan_DuLieu, int sPort_May_Nhan_DuLieu)
    {
        //loai_in:
        //          bep
        //          hoadon
        //          thanhtoan

        //0. omayin
        //1. DM_MAYIN_BEP_MA

        //in BILL
        //2.ma_phieu
        
        IPEndPoint oIPEndPoint = new IPEndPoint(IPAddress.Parse(IPMay_Nhan_DuLieu), sPort_May_Nhan_DuLieu);
        UdpClient oUdpClient = new UdpClient();
        
        try
        {
            byte[] data = Encoding.UTF8.GetBytes(loai_in + "\r\n" + sDM_MAYIN_MA + "\r\n" + _data);
            
            int i = oUdpClient.Send(data, data.Length, oIPEndPoint);
            
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message,"***");
        }
    }

    public void Send_DuLieu_Den_MayInCOM(string _data, string IPMay_Nhan_DuLieu, int sPort_May_Nhan_DuLieu)
    {
        IPEndPoint oIPEndPoint = new IPEndPoint(IPAddress.Parse(IPMay_Nhan_DuLieu), sPort_May_Nhan_DuLieu);
        UdpClient oUdpClient = new UdpClient();
        try
        {
            byte[] data = Encoding.UTF8.GetBytes(_data);
            int i = oUdpClient.Send(data, data.Length, oIPEndPoint);
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message);
        }
    }
    #endregion

    #region "   Report_Exist_Section"
    public Boolean Report_Exist_Section(ReportDocument _rpt, string _Section_Name)
    {
        foreach (Section sec in _rpt.ReportDefinition.Sections)
        {
            if (sec.Name.ToLower() == _Section_Name.ToLower())
                return true;
        }
        return false;
    }
    #endregion

    #region "   Report_Exist_Object"
    public Boolean Report_Exist_Object(ReportDocument _rpt, string _ObjectName_Name)
    {
        try
        {
            foreach (Section sec in _rpt.ReportDefinition.Sections)
            {
                foreach (ReportObject Obj in sec.ReportObjects)
                {
                    if (Obj.Name.ToLower() == _ObjectName_Name.ToLower())
                        return true;
                }
            }
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }
        return false;
    }
    #endregion

    #region Xuất dữ liệu từ GridView xang excel

    public void ATExportExcel(GridView Grid)
    {
        SaveFileDialog s = new SaveFileDialog();
        s.Filter += "*.xls|*.xls";
        if (s.ShowDialog() == DialogResult.OK)
        {
            string FN = s.FileName;
            Grid.ExportToExcelOld(FN);
        }
    }

    #endregion

}
